package org.edu.modules.jxrw.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mchange.lang.IntegerUtils;
import org.apache.commons.lang3.StringUtils;
import org.edu.common.constant.CommonConstant;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.api.vo.Result;
import org.edu.common.system.query.QueryGenerator;
import org.edu.common.util.oConvertUtils;
import org.edu.modules.jxgz.entity.VeJwSkjh;
import org.edu.modules.jxgz.service.IVeJwSkjhService;
import org.edu.modules.jxrw.api.CommonApi;
import org.edu.modules.jxrw.api.IVeJwJxzyFeignClientService;
import org.edu.modules.jxrw.api.IVeJwSkjhClientService;
import org.edu.modules.jxrw.entity.VeJwJxrw;
import org.edu.modules.jxrw.entity.VeJwPkmx;
import org.edu.modules.jxrw.service.IVeJwJxrwService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.edu.modules.jxrw.service.IVeJwPkmxService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.edu.common.aspect.annotation.AutoLog;

/**
 * @Description: ve_jw_jxrw
 * @Author: jeecg-boot
 * @Date: 2021-05-07
 * @Version: V1.0
 */
@Api(tags = "ve_jw_jxrw")
@RestController
@RequestMapping("/jxrw/veJwJxrw")
@Slf4j
public class VeJwJxrwController extends BaseController<VeJwJxrw, IVeJwJxrwService> {
    @Autowired
    private IVeJwJxrwService veJwJxrwService;

    @Autowired
    private IVeJwPkmxService veJwPkmxService;

    @Autowired
    IVeJwJxzyFeignClientService veJwJxzyFeignClientService;

    @Autowired
    IVeJwSkjhClientService veJwSkjhClientService;

    @Autowired
    private IVeJwSkjhService veJwSkjhService;

    @Autowired
    CommonApi commonApi;

    /**
     * 分页列表查询
     *
     * @param veJwJxrw
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(VeJwJxrw veJwJxrw,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        /*String xzbids = null;
        if (StringUtils.isNotEmpty(veJwJxrw.getXzbids())) {
            xzbids = veJwJxrw.getXzbids();
            veJwJxrw.setXzbids(null);
        }*/
        QueryWrapper<VeJwJxrw> queryWrapper = QueryGenerator.initQueryWrapper(veJwJxrw, req.getParameterMap());
        queryWrapper.orderByDesc("id");
        /*if (xzbids != null) {
            queryWrapper.like("xzbids", "," + xzbids + ",");
        }*/
        Page<VeJwJxrw> page = new Page<VeJwJxrw>(pageNo, pageSize);
        IPage<VeJwJxrw> pageList = veJwJxrwService.page(page, queryWrapper);
        for (VeJwJxrw item : pageList.getRecords()) {
            if (StringUtils.isNotEmpty(item.getName())) {
                String[] strings = item.getName().split("-");
                if (strings.length > 3) {
                    item.setSemester(strings[2] + "-" + strings[3]);
                    item.setClassname(strings[0]);
                }
            }
        }
        return Result.ok(pageList);
    }


    @AutoLog(value = "ve_jw_jxrw-任课情况分页列表查询")
    @ApiOperation(value = "ve_jw_jxrw-任课情况分页列表查询", notes = "ve_jw_jxrw-任课情况分页列表查询")
    @GetMapping(value = "/rklist")
    public Result<?> queryRkPageList(VeJwJxrw veJwJxrw,
                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                     HttpServletRequest req) {
        QueryWrapper<VeJwJxrw> queryWrapper = QueryGenerator.initQueryWrapper(veJwJxrw, req.getParameterMap());
        queryWrapper.orderByDesc("createTime");
        Page<VeJwJxrw> page = new Page<VeJwJxrw>(pageNo, pageSize);
        IPage<VeJwJxrw> pageList = veJwJxrwService.page(page, queryWrapper);

        //计算总周数、周节数、总节数
        int weekLessonNum = 0;
        int weekNum = 0;
        for (VeJwJxrw item : pageList.getRecords()) {
            //初始置空
            weekLessonNum = 0;
            weekNum = 0;
            List<VeJwPkmx> pkmxes = veJwPkmxService.getByJxrwid(item.getId());
            if (pkmxes.size() > 0) {
                for (VeJwPkmx pkmx : pkmxes) {
                    //周课时累加
                    weekLessonNum += pkmx.getSection();
                    //总周数
                    if (weekNum == 0) {
                        weekNum = (pkmx.getPkendweek() - pkmx.getPkstartweek() + 1);
                    }
                }
                item.setWeeklessonnum(weekLessonNum);
                item.setWeeksum(weekNum);
                item.setLessonsum(weekLessonNum * weekNum);
            }
        }

        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param veJwJxrw
     * @return
     */
    @AutoLog(value = "添加")
    @ApiOperation(value = "添加", notes = "添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeJwJxrw veJwJxrw) {
        veJwJxrwService.save(veJwJxrw);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param veJwJxrw
     * @return
     */
    @AutoLog(value = "编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeJwJxrw veJwJxrw) {
        veJwJxrwService.updateById(veJwJxrw);
        return Result.ok("编辑成功!");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通过id删除")
    @ApiOperation(value = "通过id删除", notes = "通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        /*if (veJwJxrwService.getById(id) != null) {
            veJwJxrwService.updateById(veJwJxrwService.getById(id).setDelflag(1));
            return Result.ok("删除成功!");
        }*/
        veJwJxrwService.removeById(id);
        return Result.ok("删除成功！");
    }


    /**
     * 通过id销毁
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通过id销毁")
    @ApiOperation(value = "通过id销毁", notes = "通过id销毁")
    @DeleteMapping(value = "/destroy")
    public Result<?> destroy(@RequestParam(name = "id", required = true) String id) {
        veJwJxrwService.removeById(id);
        return Result.ok("销毁成功!");
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        //this.veJwJxrwService.removeByIds(Arrays.asList(ids.split(",")));

        List<String> list = Arrays.asList(ids.split(","));
        VeJwJxrw jxrw = null;
        for (String id : list) {
            jxrw = veJwJxrwService.getById(id);
            if (jxrw != null) {
                // veJwJxrwService.updateById(jxrw.setDelflag(1));
                veJwJxrwService.removeById(id);
            }
        }

        return Result.ok("批量删除成功!");
    }


    /**
     * 批量摧毁
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "批量摧毁")
    @ApiOperation(value = "批量摧毁", notes = "批量摧毁")
    @DeleteMapping(value = "/destroyBatch")
    public Result<?> destroyBatch(@RequestParam(name = "ids", required = true) String ids) {
        veJwJxrwService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量摧毁成功!");
    }


    /**
     * 通过id还原
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通过id还原")
    @ApiOperation(value = "通过id还原", notes = "通过id还原")
    @GetMapping(value = "/restore")
    public Result<?> restore(@RequestParam(name = "id", required = true) String id) {
        if (veJwJxrwService.getById(id) != null) {
            veJwJxrwService.updateById(veJwJxrwService.getById(id).setDelflag(0));
            return Result.ok("还原成功!");
        }
        return Result.error("参数错误！");

    }

    /**
     * 批量还原
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "批量还原")
    @ApiOperation(value = "批量还原", notes = "批量还原")
    @GetMapping(value = "/restoreBatch")
    public Result<?> restoreBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        VeJwJxrw jxrw = null;
        for (String id : list) {
            jxrw = veJwJxrwService.getById(id);
            if (jxrw != null) {
                veJwJxrwService.updateById(jxrw.setDelflag(0));
            } else {
                return Result.error("参数错误！");
            }
        }
        return Result.ok("批量还原成功!");

    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "通过id查询")
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) Integer id) {
        VeJwJxrw veJwJxrw = veJwJxrwService.getById(id);
        if (veJwJxrw == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(veJwJxrw);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param veJwJxrw
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, VeJwJxrw veJwJxrw) {
        return super.exportXls(request, veJwJxrw, VeJwJxrw.class, "ve_jw_jxrw");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, VeJwJxrw.class);
    }


    /**
     * 更新合班状态
     *
     * @param veJwJxrw
     * @return
     */
    @AutoLog(value = "更新合班状态")
    @ApiOperation(value = "更新合班状态", notes = "更新合班状态")
    @PostMapping(value = "/updateIsmerged")
    public Result<?> updateIsmerged(@RequestBody VeJwJxrw veJwJxrw) {
        VeJwJxrw item = veJwJxrwService.getById(veJwJxrw.getId());
        if (item.getIsmergedclass() == 0) {
            long l = System.currentTimeMillis();
            Integer now = new Long(l).intValue();
            veJwJxrwService.updateById(item.setIsmergedclass(1).setChecktime(now));
            return Result.ok("开启合班状态成功！");
        }
        veJwJxrwService.updateById(item.setIsmergedclass(0));
        return Result.ok("关闭合班状态成功！");
    }


    /**
     * 更新发布状态
     *
     * @param id
     * @return
     */
    @AutoLog(value = "更新发布状态")
    @ApiOperation(value = "更新发布状态", notes = "更新发布状态")
    @GetMapping(value = "/changeIsPublish")
    public Result<?> changeIsPublish(@RequestParam(name = "id", required = true) String id) {
        VeJwJxrw item = veJwJxrwService.getById(id);
        if (item.getIspublish() == null || item.getIspublish() == 0) {
            if (item.getCheckstatus() == 1) {
                veJwJxrwService.updateById(item.setIspublish(1));
                return Result.ok("发布成功！");
            } else {
                return Result.error("此教学任务状态仍未通过，无法对其发布状态进行操作！");
            }
        }
        veJwJxrwService.updateById(item.setIspublish(0));
        return Result.ok("取消发布成功！");
    }


    /**
     * 批量更新发布状态
     *
     * @param ids
     * @param status
     * @return
     */
    @AutoLog(value = "批量更新发布状态")
    @ApiOperation(value = "批量更新发布状态", notes = "批量更新发布状态")
    @GetMapping(value = "/changePublishByIds")
    public Result<?> changePublishByIds(@RequestParam(name = "ids", required = true) String ids,
                                        @RequestParam(name = "status", required = true) int status) {
        veJwJxrwService.changePublishByIds(ids, status);
        return Result.ok("更新发布状态成功!");
    }


    /**
     * 一键发布
     *
     * @param veJwJxrw
     * @return
     */
    @AutoLog(value = "一键发布")
    @ApiOperation(value = "一键发布", notes = "一键发布")
    @PostMapping(value = "/oneButtonPublishing")
    public Result<?> oneButtonPublishing(@RequestBody VeJwJxrw veJwJxrw) {
        List<VeJwJxrw> list = veJwJxrwService.getByCondition(veJwJxrw);
        if (list == null || list.size() == 0) {
            return Result.error("查不到任何有关条件的教学任务信息！");
        }
        for (VeJwJxrw item : list) {
            if (item.getCheckstatus() == 1) {
                item.setIspublish(1);
            }
        }
        veJwJxrwService.updateBatchById(list);
        return Result.ok("一键发布成功！");
    }

    /**
     * 教学复用
     *
     * @param sfrom
     * @param sto
     * @return
     */
    @AutoLog(value = "ve_jw_jxrw-教学复用")
    @ApiOperation(value = "ve_jw_jxrw-教学复用", notes = "ve_jw_jxrw-教学复用")
    @GetMapping(value = "/reuse")
    public Result<?> changePublishByIds(@RequestParam(name = "sfrom", required = true) int sfrom,
                                        @RequestParam(name = "sto", required = true) int sto) {
        List<VeJwJxrw> fromlist = veJwJxrwService.getBySemid(sfrom);
        if (fromlist == null || fromlist.size() == 0) {
            return Result.error("复用学期暂无教学任务！");
        }

        int date = new Long(System.currentTimeMillis() / 1000).intValue();

        System.out.println("过滤前数据大小 ：" + fromlist.size());
        //todo 当前学期正确性判断
        //获取当前学期已有教学任务
        List<VeJwJxrw> tolist = veJwJxrwService.getBySemid(sto);

        if (tolist != null || tolist.size() != 0) {
            //对复用教学任务进行过滤避免重复插入

            List<VeJwJxrw> repeat = new ArrayList<>();
            for (int i = 0; i < fromlist.size(); i++) {
                VeJwJxrw from = fromlist.get(i);

                for (VeJwJxrw to : tolist) {
                    if ((from.getKcid().equals(to.getKcid())) &&
                            (from.getJxbid().equals(to.getJxbid())) &&
                            (from.getSpecid().equals(to.getSpecid()))) {
                        repeat.add(from);
                        break;
                    }
                }
            }
            System.out.println("重复数据数据大小 ：" + repeat.size());
            if (repeat.size() == fromlist.size()) {
                return Result.error("已完成教学复用，请勿重复提交！");
            }
            fromlist.removeAll(repeat);
            System.out.println("过滤后数据大小：" + fromlist.size());
        }


        //id置空并设置教学任务信息
        String kcmc = null;
        String kcxz = null;
        for (VeJwJxrw item : fromlist) {
            item.setId(null).setSemid(sto).setCreatetime(date);
            //todo 设置创建人,审核、发布状态是否要沿用？name设置

            //获取课程名称
            kcmc = veJwJxzyFeignClientService.getKcNameById(item.getKcid());
            switch (item.getKcxz()) {
                case 1:
                    kcxz = "公共基础课教学任务";
                    break;
                case 2:
                    kcxz = "学科基础课教学任务";
                    break;
                case 3:
                    kcxz = "必修课教学任务";
                    break;
            }
            item.setName("测试班级id" + item.getJxbid() + "-" + kcmc + "-学期id" + sto + "-学制id" + item.getXzid() + "-" + kcxz);
        }

        veJwJxrwService.saveBatch(fromlist);
        return Result.OK("复用成功！");
    }

    /**
     * 获取可制定授课计划的任务列表
     *
     * @param veJwJxrw
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "ve_jw_jxrw-我的教学任务")
    @ApiOperation(value = "ve_jw_jxrw-我的教学任务", notes = "ve_jw_jxrw-我的教学任务")
    @GetMapping("/my/list")
    public Result<?> getMyJxrwList(VeJwJxrw veJwJxrw,
                                   @RequestParam(defaultValue = "1") int pageNo,
                                   @RequestParam(defaultValue = "5") int pageSize) {

        LambdaQueryWrapper<VeJwJxrw> wrapper = new LambdaQueryWrapper<>();
        // 执行学期ID
        if (veJwJxrw.getSemid() != null) {
            wrapper.eq(VeJwJxrw::getSemid, veJwJxrw.getSemid());
        }
        // 专业组
        if (veJwJxrw.getFalid() != null) {
            wrapper.eq(VeJwJxrw::getFalid, veJwJxrw.getFalid());
        }
        // 专业
        if (veJwJxrw.getSpecid() != null) {
            wrapper.eq(VeJwJxrw::getSpecid, veJwJxrw.getSpecid());
        }
        // 根据创建时间逆序
        wrapper.orderByDesc(VeJwJxrw::getCreatetime);

        // 状态：通过
        wrapper.eq(VeJwJxrw::getCheckstatus, CommonConstant.STATUS_1);
        // 发布
        wrapper.eq(VeJwJxrw::getIspublish, CommonConstant.STATUS_1);
        // 未删除
        wrapper.eq(VeJwJxrw::getDelflag, CommonConstant.DEL_FLAG_0);

        Page<VeJwJxrw> page = new Page<>(pageNo, pageSize);
        IPage<VeJwJxrw> pageList = veJwJxrwService.page(page, wrapper);
        for (VeJwJxrw item : pageList.getRecords()) {
            String[] strings = item.getName().split("-");
            item.setSemester(strings[2] + "-" + strings[3]);
            item.setClassname(strings[0]);
            // 授课计划是否制定
            //Result<JSONObject> data = veJwSkjhClientService.queryById(item.getId());
            //item.setSkjh(data.getResult());
            LambdaQueryWrapper<VeJwSkjh> skjhWrapper = new LambdaQueryWrapper<>();
            skjhWrapper.eq(VeJwSkjh::getJxrwid, item.getId());
            VeJwSkjh veJwSkjh = veJwSkjhService.getOne(skjhWrapper);
            item.setSkjh(veJwSkjh);
        }
        return Result.OK(pageList);
    }

    /**
     * 可复制授课计划列表
     *
     * @param jxrwId
     * @return
     */
    @AutoLog(value = "ve_jw_jxrw-可复制授课计划列表")
    @ApiOperation(value = "ve_jw_jxrw-可复制授课计划列表", notes = "ve_jw_jxrw-可复制授课计划列表")
    @GetMapping("/copy/list")
    public Result<?> getCopyableJxrwList(Integer jxrwId) {

        // 教学任务信息
        VeJwJxrw jwJxrw = veJwJxrwService.getById(jxrwId);

        LambdaQueryWrapper<VeJwJxrw> wrapper = new LambdaQueryWrapper<>();
        // 获取一致的课程
        wrapper.eq(VeJwJxrw::getKcid, jwJxrw.getKcid());
        // 排除本教学任务
        wrapper.ne(VeJwJxrw::getId, jxrwId);
        // 根据创建时间逆序
        wrapper.orderByDesc(VeJwJxrw::getCreatetime);
        // 状态：通过
        wrapper.eq(VeJwJxrw::getCheckstatus, CommonConstant.STATUS_1);
        // 发布
        wrapper.eq(VeJwJxrw::getIspublish, CommonConstant.STATUS_1);
        List<VeJwJxrw> tempList = veJwJxrwService.list(wrapper);

        // 最终返回的数组
        List<VeJwJxrw> result = Lists.newArrayList();
        for (VeJwJxrw item : tempList) {
            String[] strings = item.getName().split("-");
            item.setSemester(strings[2] + "-" + strings[3]);
            item.setClassname(strings[0]);
            // 授课计划是否制定
            Result<JSONObject> data = veJwSkjhClientService.queryById(item.getId());
            // 未完成的授课计划 或 未制定的 才能进行复制
            if (data.getResult() == null || data.getResult().getInteger("iscomplete") == 0) {
                result.add(item);
            }
        }
        IPage<VeJwJxrw> pageList = new Page<>();
        pageList.setRecords(result);
        return Result.OK(pageList);
    }

    /**
     * 获取行政班列表
     *
     * @param semId 学期ID
     * @param kcId  课程ID
     * @return
     */
    @AutoLog(value = "ve_jw_jxrw-获取行政班列表")
    @ApiOperation(value = "ve_jw_jxrw-获取行政班列表", notes = "ve_jw_jxrw-获取行政班列表")
    @GetMapping("/xzbs")
    public Result<?> getXzbList(@RequestParam Integer semid, @RequestParam Integer kcid) {

        LambdaQueryWrapper<VeJwJxrw> wrapper = new LambdaQueryWrapper<>();
        // 根据条件进行筛选
        wrapper.eq(VeJwJxrw::getSemid, semid);
        wrapper.eq(VeJwJxrw::getKcid, kcid);

        // 状态：通过
        wrapper.eq(VeJwJxrw::getCheckstatus, CommonConstant.STATUS_1);
        // 发布
        wrapper.eq(VeJwJxrw::getIspublish, CommonConstant.STATUS_1);
        // 获取教学任务列表
        List<VeJwJxrw> jxrwList = veJwJxrwService.list(wrapper);
        // 查询行政班信息
        List<JSONObject> data = Lists.newArrayList();
        for (VeJwJxrw item : jxrwList) {
            String[] ids = item.getXzbids().split(",");
            for (int i = 1; i < ids.length; i++) {
                JSONObject object = commonApi.queryBanJiById(CommonApi.COMMON_TOKEN_KEY, Integer.valueOf(ids[i])).getResult();
                // 添加专业组
                object.put("falid", item.getFalid());
                // 添加专业
                object.put("specid", item.getSpecid());
                // 添加学期
                object.put("semid", semid);
                // 添加课程
                object.put("kcid", kcid);
                // 获取班级人数
                JSONObject bjData = commonApi.getStudentPageList(CommonApi.COMMON_TOKEN_KEY, Integer.valueOf(ids[i]), 1).getResult();
                object.put("number", bjData.getInteger("total"));

                data.add(object);
            }
        }

        IPage<JSONObject> pageList = new Page<>();
        pageList.setRecords(data);

        return Result.OK(pageList);
    }
}
